<template>
	<cu-page-base :nav-bar-options="navBarOptions" @clickNavBarLeft="goBack">
		<view class="cu-px-20 cu-w-100 cu-pt-20" style="padding-bottom: 140rpx;">
			<view
				class="cu-p-20 cu-bg-main cu-border-r-10 cu-shadow cu-w-100 cu-d-flex cu-j-sb cu-a-stretch cu-flex-column">
				<view class="cu-tools cu-w-100 cu-py-10 cu-row cu-j-start cu-a-center"
					style="height: 80rpx; line-height: 60rpx;">
					<view class="cu-row cu-a-center cu-pr-20"><button @click="copyBtn" class="mini-btn" type="primary"
							size="mini">粘贴文案</button></view>
					<view @click="clearBtn" class="cu-row cu-a-center cu-pr-20"><button class="mini-btn" type="default"
							size="mini">清空文案</button></view>
					<view></view>
				</view>
				<view class="cu-w-100 cu-py-10 cu-d-flex cu-j-sb cu-a-stretch cu-flex-column"
					style="border: 1px dotted #CCC;">
					<editor id="editor" class="ql-container cu-w-100 cu-px-20" :style="{height:editorHeight + 'px'}"
						@ready="editorReady" show-img-toolbar='true' show-img-resize="true" @input="editorInput" />
					<view class="cu-w-100 cu-row cu-j-start cu-a-center">
						<view @touchend="funBtn('dyz')" class="cu-row cu-a-center cu-px-10"><button class="mini-btn"
								type="default" size="mini">多音字</button></view>
						<view @touchend="funBtn('td')" class="cu-row cu-a-center cu-px-10"><button class="mini-btn"
								type="default" size="mini">停顿</button></view>
					</view>
					<view class="cu-w-100 cu-row cu-j-end cu-pr-20">
						{{voiceStore.text ? (voiceStore.text.length - 1) : 0}}/3000
					</view>
				</view>
			</view>
			<view class="cu-w-100 cu-pt-20 ">
				<view
					class="cu-w-100 cu-py-20 cu-bg-main cu-border-r-10 cu-shadow cu-d-flex cu-j-sb cu-a-stretch cu-flex-column">
					<view class="cu-px-20 cu-row cu-j-sb cu-a-center ">
						<view @click="gotoPage('/pages/voice/voices/voices','navigate')"
							class="cu-row cu-j-start cu-a-center">
							<u--image :src="'/static/images/kf/kf' + voiceStore.voice.imageType + '.png'" width="80"
								height="80" shape="circle"></u--image>
							<view class="cu-d-flex cu-j-sb cu-flex-column">
								<view class="cu-font-lg cu-font-weight"><text
										class="cu-pr-20">{{voiceStore.voice.name}}</text><uni-icons type="bottom"
										size="14"></uni-icons></view>
								<view class="cu-font-sm">
									<block v-for="(item,idx) in voiceStore.voice.label">
										<text :key="idx" class="cu-px-20 cu-py-10 cu-border-r-10 cu-mr-10"
											:style="{backgroundColor: item.backgroundColor}">{{item.text}}</text>
									</block>

								</view>
							</view>
						</view>
						<view v-if="voiceStore.voice.isEmotional" @click="changeEmotional"
							class="cu-row cu-j-start cu-a-center">
							<view class="cu-px-20">情感风格</view>
							<view class="cu-py-10 cu-mr-10"><text
									style="border-bottom: 1px solid #3e3e7e;">{{voiceStore.voice.emotional | emotionalFormat}}</text>
								<uni-icons class="cu-pl-20" type="bottom" size="14"></uni-icons>
							</view>
						</view>
					</view>
					<view class="cu-px-20 cu-pt-20 cu-row cu-j-sb cu-a-center ">
						<view class="cu-span24-4">情感程度</view>
						<view class="cu-span24-17">
							<u-slider v-model="voiceStore.emotion" @input="emotionInput" step="10" min="50"
								max="200"></u-slider>
						</view>
						<view class="cu-span24-3">{{voiceStore.emotion}}</view>
					</view>
					<view class="cu-px-20 cu-pt-20 cu-row cu-j-sb cu-a-center ">
						<view class="cu-span24-4">音速</view>
						<view class="cu-span24-17">
							<u-slider v-model="voiceStore.sonicSpeed" @input="sonicSpeedInput" step="0.1" min="-2"
								max="2.5"></u-slider>
						</view>
						<view class="cu-span24-3">{{voiceStore.sonicSpeed}}</view>
					</view>
					<view class="cu-px-20 cu-pt-20 cu-row cu-j-sb cu-a-center ">
						<view class="cu-span24-4">音量</view>
						<view class="cu-span24-17">
							<u-slider v-model="voiceStore.volume" @input="volumeInput" step="1" min="0"
								max="10"></u-slider>
						</view>
						<view class="cu-span24-3">{{voiceStore.volume}}</view>
					</view>
					<view class="cu-px-20 cu-pt-20 cu-row cu-j-sb cu-a-center ">
						<view class="cu-span24-4">文件格式</view>
						<view class="cu-span24-17">
							<view class="cu-row cu-j-center">
								<radio-group @change="fileTypeChange">
									<label class="radio">
										<radio value="wav" :checked="voiceStore.fileType === 'wav'" />wav
									</label>
									<label class="radio cu-px-20">
										<radio value="mp3" :checked="voiceStore.fileType === 'mp3'" />mp3
									</label>
									<label class="radio">
										<radio value="pcm" :checked="voiceStore.fileType === 'pcm'" />pcm
									</label>
								</radio-group>
							</view>
						</view>
						<view class="cu-span24-3"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-position-fixed cu-px-40 cu-pt-20 cu-pb-20 cu-bottom-0 cu-w-100 cu-bg-main"
			style="height: 120rpx;">
			<view class="cu-w-100 cu-row cu-j-sb">
				<view @click="auditionFun" class="cu-row cu-font-lg cu-a-center">
					<u-icon name="play-circle-fill"></u-icon><text class="cu-pl-10">试听</text>
				</view>
				<view @click="synthesisFun"><u-button text="合成" shape="circle" :customStyle="{width: '240rpx'}"
						color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"></u-button></view>
				<view @click="gotoPage('/pages/voice/record/list','navigate')" class="cu-row cu-font-lg cu-a-center">
					<uni-icons type="cloud-download-filled" size="16"></uni-icons><text class="cu-pl-10">下载</text>
				</view>
			</view>
		</view>

		<u-picker itemHeight="80" @cancel="emotionalCancel" @confirm="emotionalConfirm" :show="showEmotionalPicker"
			:columns="emotionaColumns" keyName="label"></u-picker>
		<u-modal :show="showModal" @close="closeModal" @cancel="closeModal" @confirm="confirmModal" ref="uModal"
			:title="modal.title" :content='modal.content' :zoom="true" :showCancelButton="true"
			:closeOnClickOverlay="true"></u-modal>
		<uni-popup ref="pausePopup" type="bottom" background-color="#f8f8f8">
			<view class="cu-w-100 cu-p-20">
				<view class="cu-w-100 cu-pt-20 cu-d-flex cu-flex-column cu-j-sb cu-a-stretch">
					<view @touchend="insertPause(200)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">200毫秒</text>
					</view>
					<view @touchend="insertPause(300)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">300毫秒</text>
					</view>
					<view @touchend="insertPause(500)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">500毫秒</text>
					</view>
					<view @touchend="insertPause(1000)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">1秒</text>
					</view>
					<view @touchend="insertPause(2000)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">2秒</text>
					</view>
					<view @touchend="insertPause(3000)" class="cu-w-100 cu-text-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text style="border-bottom: 1px solid #3e3e7e;">3秒</text>
					</view>
					<view class="cu-w-100 cu-text-center cu-row cu-j-center cu-a-center"
						style="height: 60rpx;line-height: 60rpx;">
						<text class="cu-pr-20">自定义</text>
						<input v-model="pauseInputVal" class="uni-input cu-border-r-10" type="number" placeholder="请输入"
							maxlength="5" style="width: 100rpx;border: 1px solid #3e3e7e;" />
						<view @touchend="insertPause(pauseInputVal)" class="cu-row cu-j-center cu-a-center cu-pl-20">
							<button class="mini-btn" type="default" size="mini">确认</button>
						</view>
					</view>
					<view class="cu-w-100 cu-text-center" style="height: 60rpx;line-height: 60rpx;">
						<text>提示：自定义取值范围为[50, 10000]的整数，单位毫秒</text>
					</view>
				</view>
			</view>
		</uni-popup>
	</cu-page-base>

</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import commMiXin from '@/common/mixin/common-mixin.js';
	const {
		pauseVal
	} = require('@/pages/voice/utils/request/request-utils')
	const {
		apiPostText2audioGenText,
		apiPostText2audio,
		apiPostLongText2audio
	} = require('@/pages/voice/utils/api/index')
	const {
		longTextSplit
	} = require("@/pages/voice/utils/voice/index")
	export default {
		mixins: [commMiXin],
		computed: {
			...mapState({
				commonStore: state => state.commonStore,
				voiceStore: state => state.voiceStore,
				loginStore: state => state.loginStore,
			})
		},
		filters: {
			emotionalFormat(val) {
				let type = val;
				switch (val) {
					case "neutral":
						type = "中性";
						break;
					case "sad":
						type = "悲伤";
						break;
					case "happy":
						type = "高兴";
						break;
					case "angry":
						type = "生气";
						break;
					case "fear":
						type = "恐惧";
						break;
					case "news":
						type = "新闻";
						break;
					case "story":
						type = "故事";
						break;
					case "radio":
						type = "广播";
						break;
					case "poetry":
						type = "诗歌";
						break;
					case "call":
						type = "客服";
						break;
					default:
				}
				return type;
			},
		},
		data() {
			return {
				showModal: false,
				showEmotionalPicker: false,
				emotionaColumns: [
					[{
						label: '中性',
						value: "neutral"
					}, {
						label: '悲伤',
						value: "sad"
					}, {
						label: '高兴',
						value: "happy"
					}, {
						label: '生气',
						value: "angry"
					}, {
						label: '恐惧',
						value: "fear"
					}, {
						label: '新闻',
						value: "news"
					}, {
						label: '故事',
						value: "story"
					}, {
						label: '广播',
						value: "radio"
					}, {
						label: '诗歌',
						value: "poetry"
					}, {
						label: '客服',
						value: "call"
					}]
				],
				modelType: "",
				modal: {
					title: '温馨提示',
					content: '您尚未登录，是否前往登录？'
				},
				navBarOptions: {
					title: "语音合成-免费配音神器",
					leftText: "返回",
					leftIcon: "back",
				},
				editorHeight: 300,
				editorCtx: undefined,
				// 情感程度
				emotion: 100,
				// 音速
				sonicSpeed: 1,
				// 音量
				volume: 5,
				pauseInputVal: null,
			};
		},
		async onLoad() {
			if (this.loginStore && this.loginStore.userinfo === undefined) {
				this.modelType = "login";
				this.showModal = true;
			} else {
				await this.$store.dispatch('voiceStore/initVoice');
			}
			if (this.showModal == true) {
				this.showModal = false;
			}

		},
		onShow() {
			this.editorReady();
		},
		methods: {

			closeModal() {
				this.showModal = false;
			},
			async confirmModal() {
				this.showModal = false;
				if (this.modelType === "clear") {
					await this.$store.dispatch('voiceStore/clear');
					this.editorCtx.setContents({
						html: ""
					});
				} else if (this.modelType === "login") {
					this.gotoPage("/pages/oauth/loginbywx/loginbywx", "navigate");
				}
			},
			clearBtn() {
				this.showModal = true;
				this.modelType = "clear";
				this.modal.content = "确认清空文本么？"
			},
			editorReady() {
				const that = this
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editor');
				// #endif

				// #ifdef APP-PLUS || H5 ||MP-WEIXIN
				uni.createSelectorQuery().select('#editor').context((res) => {
					that.editorCtx = res.context
					that.editorCtx.setContents({
						html: that.voiceStore.html !== undefined ? that.voiceStore.html : ""
					});

				}).exec()
				// #endif
			},
			editorInput(data) {
				const {
					delta,
					html,
					text
				} = data.detail
				this.$store.dispatch('voiceStore/setInput', {
					delta,
					html,
					text
				});
			},
			// 选择情感
			changeEmotional() {
				this.showEmotionalPicker = true
			},
			// 情感选择取消
			emotionalCancel() {
				this.showEmotionalPicker = false
			},
			// 情感选择确认
			emotionalConfirm(e) {
				const {
					label,
					value
				} = e.values[0][e.indexs]
				this.voiceStore.voice.emotional = value
				this.showEmotionalPicker = false
			},
			copyBtn() {
				const that = this
				uni.getClipboardData({
					success: async function(res) {
						const data = {
							delta: {
								ops: [{
									insert: (that.voiceStore.delta && that.voiceStore
										.delta.ops[0].insert ? that.voiceStore.delta
										.ops[0].insert : "") + "\n" + res.data.replaceAll(
										"\r\n", "\n").replaceAll("\t", "")
								}]
							},
							html: (that.voiceStore.html ? that.voiceStore.html : "") + "<p>" +
								res.data.replaceAll("\r\n", "\n").replaceAll("\t", "") + "</p>",
							text: (that.voiceStore.text ? that.voiceStore.text : "") + "\n" +
								res.data.replaceAll("\r\n", "\n").replaceAll("\t", "")
						}
						await that.$store.dispatch('voiceStore/setInput', {
							delta: data.delta,
							html: data.html,
							text: data.text
						});
						that.editorCtx.setContents({
							html: data.html
						});
					}
				});
			},
			volumeInput(value) {
				this.voiceStore.volume = value
			},
			sonicSpeedInput(value) {
				this.voiceStore.sonicSpeed = (Math.ceil(value * 10) / 10).toFixed(1)
			},
			emotionInput(value) {
				this.voiceStore.emotion = value
			},
			fileTypeChange(e) {
				const {
					value
				} = e.detail
				this.voiceStore.fileType = value
			},
			/* 试听 */
			auditionFun() {
				
				if (this.loginStore && this.loginStore.userinfo === undefined) {
					uni.showModal({
						title: '提示',
						content: "您暂未登录",
						cancelText: '取消',
						confirmText: '去登录',
						success: async function(res) {
							const {
								cancel,
								confirm
							} = res
							// 确认
							if (confirm === true) {
								that.gotoPage("/pages/tabbar/mine/mine", "switchTab");
							}
						}
					});
				} else if (this.voiceStore.text && this.voiceStore.text.length > this.voiceStore.maxSynthesisLength) {
					uni.showModal({
						title: '提示',
						content: '合成内容暂不能超过3000字符',
						confirmText: '确认',
						showCancel: false,
						success: function() {

						}
					});
				} else if (this.voiceStore.text && this.voiceStore.text.length > 1 && this.voiceStore.text.length <= 3001) {
					this.gotoPage("/pages/voice/audition/audition", "navigate")
				}
			},
			/* 合成 */
			synthesisFun() {
				const that = this
				/* if(true){
					console.log(textToSsml(this.voiceStore.text))
				}else */
				if (this.loginStore && this.loginStore.userinfo === undefined) {
					uni.showModal({
						title: '提示',
						content: "您暂未登录",
						cancelText: '取消',
						confirmText: '去登录',
						success: async function(res) {
							const {
								cancel,
								confirm
							} = res
							// 确认
							if (confirm === true) {
								that.gotoPage("/pages/tabbar/mine/mine", "switchTab");
							}
						}
					});
				} else if (this.voiceStore.text && this.voiceStore.text.length > this.voiceStore.maxSynthesisLength) {
					uni.showModal({
						title: '提示',
						content: '合成内容暂不能超过150字符',
						confirmText: '确认',
						showCancel: false,
						success: function() {

						}
					});
				} else if (this.voiceStore.text && this.voiceStore.text.length > 1 && this.voiceStore.text.length < 151) {

					const uid = this.loginStore.userinfo._id
					uni.showModal({
						title: '提示',
						content: '当前合成消耗' + (this.voiceStore.text.length - 1) + "个字符，是否合成",
						cancelText: '取消',
						confirmText: '确认',
						success: async function(res) {
							const {
								cancel,
								confirm
							} = res
							// 确认
							if (confirm === true) {
								// await that.$store.dispatch('voiceStore/textToSpeech',{uid,that:that});
								await apiPostText2audio(uid, that.voiceStore).then(async apiRes => {
									const {
										text,
										fileID,
										SessionId,
										Subtitles
									} = apiRes
									await that.$store.dispatch(
										'voiceStore/textToSpeech', {
											uid,
											that,
											text,
											fileID,
											SessionId,
											Subtitles
										});
									uni.hideLoading();
									uni.showModal({
										title: '提示',
										content: '合成成功',
										confirmText: '去下载',
										cancelText: "取消",
										success: function(res) {
											if (res.confirm) {
												uni.redirectTo({
													url: "/pages/voice/record/list"
												});
											} else {
												uni.switchTab({
													url: "/pages/tabbar/index/index"
												});
											}
										}
									});
								}).catch(res => {
									console.error(res)
									uni.hideLoading();
									uni.showModal({
										title: '提示',
										content: '合成失败，请稍后重试',
										confirmText: '确认',
										showCancel: false,
									});
								})
							}
						},
						fail: (res) => {
							console.error(res)
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '合成失败，请稍后重试',
								confirmText: '确认',
								showCancel: false,
							});
						},
						complete: () => {

						}
					});
				} else if (this.voiceStore.text && this.voiceStore.text.length > 1 && this.voiceStore.text.length < (this
						.voiceStore.maxSynthesisLength + 1)) {
					console.log("长文本语音合成-开始")
					const longTextSplitArr = longTextSplit(this.voiceStore.text);
					const uid = this.loginStore.userinfo._id;
					// console.log("longTextSplitArr",longTextSplitArr)
					uni.showModal({
						title: '提示',
						content: '合成过程中，请不要退出当前页面，当前合成消耗' + (this.voiceStore.text.length - 1) + "个字符，是否合成",
						cancelText: '取消',
						confirmText: '确认',
						success: async function(res) {
							const {
								cancel,
								confirm
							} = res

							// 确认
							if (confirm === true) {
								// await that.$store.dispatch('voiceStore/textToSpeech',{uid,that:that});
								console.log("语音合成开始")
								await apiPostLongText2audio(uid, that.voiceStore, longTextSplitArr).then(
								async apiRes => {
										const {
											fileID,
											sessionId,
											subtitlesData
										} = apiRes

										await that.$store.dispatch(
											'voiceStore/textToSpeech', {
												uid,
												that,
												text: that.voiceStore.text,
												fileID,
												SessionId: sessionId,
												Subtitles: subtitlesData
											});
										uni.hideLoading();
										uni.showModal({
											title: '提示',
											content: '合成成功',
											confirmText: '去下载',
											cancelText: "取消",
											success: function(res) {
												if (res.confirm) {
													uni.redirectTo({
														url: "/pages/voice/record/list"
													});
												} else {
													uni.switchTab({
														url: "/pages/tabbar/index/index"
													});
												}
											}
										});

									}).catch(async res => {
										console.error("合成失败",res)
										if (res != null && res.consume != null && res.consume > 0) {
											const sessionId = uid + "-" + that.voiceStore.text.length + "-" + new Date()
												.getTime();
											await that.$store.dispatch(
												'voiceStore/textToSpeech', {
													uid,
													that,
													text: that.voiceStore.text,
													fileID: null,
													SessionId: sessionId,
													Subtitles: null,
													recordstate: 4
												});
										}
										uni.hideLoading();
										uni.showModal({
											title: '提示',
											content: '合成失败，请稍后重试',
											confirmText: '确认',
											showCancel: false,
										});
								})
							}
						},
						fail: (res) => {
							console.error("合成失败",res)
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '合成失败，请稍后重试',
								confirmText: '确认',
								showCancel: false,
							});
						}
					});

					console.log("长文本语音合成-结束")
				}
			},
			funBtn(type) {
				console.log("type", type)
				if (type === "td") {
					this.pauseInputVal = null
					this.$refs.pausePopup.open()
				} else if (type === "dyz" && this.voiceStore.text && this.voiceStore.text.length > 1) {
					this.gotoPage("/pages/voice/index/identify", "navigate")
				}
			},
			/* 插入停顿 */
			insertPause(val) {
				if (val === null) {
					uni.showToast({
						icon: "error",
						title: "请输出参数"
					})
					return
				}
				const resp = pauseVal(val)
				if (resp !== undefined) {
					this.$refs.pausePopup.close()
					this.editorCtx.insertText({
						text: "[停顿:" + resp + "]"
					});
				}

			},
			goBack(data) {
				this.gotoPage(1, 'navigateBack');
			},
		}
	}
</script>

<style lang="scss">

</style>